package com.zhentao.file.service.impl;


import com.zhentao.file.config.MinioConfig;
import com.zhentao.file.config.MinioConfigProperties;
import com.zhentao.file.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;


@EnableConfigurationProperties(MinioConfigProperties.class)
@Import(MinioConfig.class)

public class FileStorageServiceImpl implements FileStorageService {
    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioConfigProperties minioConfigProperties;
    @Override
    public String uploadHtmlFile(String fileName, InputStream inputStream) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //文件名的处理
        fileName= UUID.randomUUID()+fileName;
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fileName)
                .contentType("text/html")
                .stream(inputStream, inputStream.available(), -1)
                .build();
        minioClient.putObject(putObjectArgs);
        String url = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
        return url;
    }

    @Override
    @SneakyThrows
    public String uploadImageFile(String fileName, InputStream inputStream) {
        //sadffsddfs.png
        String fname = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));


        //2. 设置上传参数
        PutObjectArgs poa = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fname)
                .contentType("image/jpeg")  // 根据实际图片格式设置 MIME 类型
                .stream(inputStream, inputStream.available(), -1)
                .build();

// 确保 bucket 存在


//3. 上传文件
        minioClient.putObject(poa);

// 获取文件 URL
        String url = minioClient.getObjectUrl(poa.bucket(), poa.object());
        System.out.println(url);
        return url;
    }
}
